<template>
  <n-modal v-model:show="show"
           class="max-w-md"
           :mask-closable="false"
           preset="card"
           :bordered="false">
    <n-form ref="formRef" :model="form" :rules="rules" class="p-5">
      <div class="flex space-x-2">
        <n-form-item path="host" label="主机" class="w-2/3">
          <n-input v-model:value="form.host" placeholder="主机"/>
        </n-form-item>
        <n-form-item path="port" label="端口" class="w-1/3">
          <n-input v-model:value="form.port" placeholder="端口"/>
        </n-form-item>
      </div>
      <n-form-item path="password" label="密码">
        <n-input type="password" v-model:value="form.password" placeholder="密码"/>
      </n-form-item>
      <n-button :loading="loading" @click="handleConnect" block class="bg-green-600 dark:bg-green-400"
                type="success">
        连接
      </n-button>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref} from "vue";
import {debounce, renderIcon} from "@/utils";
import api from "@/api";
import {useDatabaseStore} from "@/store";


const emits =defineEmits( ['onConnect'])
const databaseStore = useDatabaseStore()
const loading = ref(false)
const form = ref({
  host: '',
  password: '',
  port: '',
})
const formRef = ref()
const rules = ref({
  host: [{
    required: true,
    message: '请选择主机',
    trigger: ['input']
  }],
  port: [{
    required: true,
    message: '请选择端口号',
    trigger: ['input']
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: ['input']
  }],
})
const show = ref(false)


const handleConnect = debounce(() => {
  formRef.value.validate((error: any) => {
    if (!error) {
      loading.value = true
      api.redis.connect({
        ...form.value
      }).then((res: any) => {
        if (res.data.code === 0) {
          emits('onConnect', res.data.data)
          add(res.data.data)
          window.$message.success(res.data.msg)
        }
      }).finally(() => {
        loading.value = false
        show.value = false
      })
    }
  })
}, 200)


const add = (info: any) => {
  let children: IDatabaseItem[] = []
  for (let i = 0; i < 16; i++) {
    children.push({
      label: 'db' + i,
      key: 'db' + i,
    })
  }
  let db: IDatabase = {
    label: form.value.host + ':' + form.value.port,
    icon: renderIcon('material-symbols:database'),
    key: form.value.host + ':' + form.value.port,
    children: children,
    info: info,
    name: form.value.host + ':' + form.value.port,
    available:true
  }
  databaseStore.pushDb(db)
}

const doParamsShow = (params: any) => {
  show.value = true
  form.value = params
}

const doShow = () => {
  show.value = true
}
const doHide = () => {
  show.value = false
}
defineExpose({
  doShow,
  doHide,
  doParamsShow
})

</script>
<style scoped>

</style>
<style>
.n-card.n-modal {
  border-radius: 15px;
}
</style>

